import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';

import { CategroyComponentService } from './categroy.component.service';

import { AlertsService } from '../../modules/ng2-alerts';

import { Util } from "../../utils/util";

import { CategoryName } from '../../pipes/categoryNamePipe';

import { AppSettings } from '../../app.settings';

import { AsyncLocalStorage } from 'angular-async-local-storage';

declare var $: any;

@Component({
  selector: 'app-categroy',
  templateUrl: './categroy.component.html',
  styleUrls: ['./categroy.component.css'],
  providers: [CategroyComponentService, CategoryName, AlertsService]
})
export class CategroyComponent implements OnInit {

  @Input('onlyLeaf') onlyLeaf: boolean;//只有叶子可以点击
  @Input('option') option: any;
  //{defaultText:true||false,onlyLevelOne:true||false}
  // onlyLevelOne 只有一级菜单
  // cat   保存的历史类目:string

  @Output('onChangeCat') onChangeCat: EventEmitter<any> = new EventEmitter<any>();

  constructor(private _service: CategroyComponentService, private util: Util, private categoryName: CategoryName, private alertsService: AlertsService, private appSettings: AppSettings, private asyncStore: AsyncLocalStorage) { }

  user: any;

  // root
  rootCat: any = {
    catName: '',
    categoryId: '',
    wholeName: ''
  };

  vm: any = {
    selectText: "",
    category: '',
    cat: '',
    activeItemsArrry: [],
    set: (text, category, cat) => {

      this.vm.selectText = text;

      this.vm.category = category;

      this.vm.cat = cat;
    }
  };

  // 菜单
  tree: any = [];

  userCategorys: any = [];


  ngOnInit() {

    /* // store
     this.asyncStore.getItem('localCats').subscribe((data)=>{
 
       // 用户关注的类目
       this.userCategorys = data;
 
       // 初始化user
       this.userCatGet();
 
     });*/

    this.init();



    // 点击取消
    $(document.body).on("click", (e) => {

      if (($(".globalCategory").find($(e.target)).length > 0) || ($(e.target).hasClass('globalCategory'))) {

      } else {
        this.hideElement();
      }
    });

  }

  ngOnDestroy() {
    this.onChangeCat.unsubscribe();

    if (this.offEvent) {
      this.offEvent.unsubscribe();
    }

    if (this.catEvent) {
      this.catEvent.unsubscribe();
    }

  }
  catEvent: any;
  init() {
    var res = { "code": 0, "msg": "成功", "data": [{ "id": 964, "type": 4, "target": "50019780", "userId": 5, "value": "数码/手机/家电--平板电脑/MID", "createTime": 1508895423000 }] };


    if (res.data.length > 0) {
      for (let i in res.data) {
        let item:any = Object.assign({},res.data[i]);
        item.cat = {};
        item.cat = {
          catName: item.value,
          wholeName: item.value,
          categoryId: item.target
        };
      }


      // 用户关注的类目
      this.userCategorys = res.data;

      // 初始化user
      this.userCatGet();


    } else {

      this.userCategorys = [];
    }


  }




  // 根据user类目来init
  userCatGet() {

    // this.user = this.util.sessionStore().get('user');

    this.userCategorysInit();

    console.log(this.appSettings.getAppCat());

    console.log(this.util.isEmptyObject(this.appSettings.getAppCat()));

    if (this.appSettings.getAppCat().categoryId) {
      Object.assign(this.rootCat, this.appSettings.getAppCat());

    } else {
      Object.assign(this.rootCat, this.userCategorys[0].cat);
    }



    // console.log(this.rootCat);



    // this.levelInit();

    // 是否有保存的历史 --no
    if (this.option && (typeof this.option.cat == "undefined")) {

      // 设置cat text
      this.vm.set(this.categoryName.transform(this.rootCat.catName), this.rootCat.categoryId, this.rootCat.wholeName);

      // 向Output emit
      this.onChangeCat.emit({ wholeName: this.rootCat.wholeName, categoryId: this.rootCat.categoryId, catName: this.categoryName.transform(this.rootCat.catName) });
    }


  }

  userCategorysInit() {

    console.log(this.userCategorys);
    let _tree = [];



    for (let i = 0; i < this.userCategorys.length; i++) {
      let _item = this.userCategorys[i].cat;
      _item.level = 2;
      _tree.push({
        label: this.categoryName.transform(_item.catName),
        data: {
          source: {
            wholeName: _item.wholeName,
            id: _item.categoryId,
            name: this.categoryName.transform(_item.catName),
            level: 2
          }

        },
        noLeaf: ((this.option && this.option.onlyLevelOne && _item.level == 2) || _item.categoryId > 0) ? true : false,

        children: []
      });
    }
    this.tree = _tree;

    // 是否有保存的历史
    if (this.option && (typeof this.option.cat != "undefined")) {

      this.history(2);
    } else {
      this.activeItemsArrry.length = 0;
    }

    console.log(this.tree);
  }


  // init不需要
  levelInit() {

    // 是否是全类目
    let _p: any = this.rootCat.categoryId == -1 ? { level: 1 } : { level: 3, catName: this.rootCat.wholeName };


    // 店铺page的类目要上一级
    if (_p.level === 3 && this.option && this.option.onlyLevelOne) {

      _p.level = 2;
      _p.catName = _p.catName.split('--')[0];
    }

    this._service.get(_p).subscribe((res: any) => {

      let data = res.data;

      let _tree = [];

      for (let i = 0; i < data.length; i++) {
        let _item = data[i];

        _tree.push({
          label: _item.name,
          data: {
            source: _item
          },
          noLeaf: (this.option && this.option.onlyLevelOne && _p.level == 2) ? true : false,

          children: []
        });
      }


      //是否给一个默认值(店铺的类目需要向上扩张，不需要默认值)
      if (this.option && this.option.defaultText && (typeof this.option.onlyLevelOne == "undefined")) {
        _tree.unshift({
          label: this.rootCat.catName,
          noLeaf: true,
          data: {
            source: {
              wholeName: this.rootCat.wholeName,
              id: this.rootCat.categoryId,
              name: this.rootCat.catName
            }
          }

        });

        setTimeout(() => {
          // 默认
          this.setActiveLi(0, 1);
        }, 1000);

      }

      this.tree = _tree;


      // 是否有保存的历史
      if (this.option && (typeof this.option.cat != "undefined")) {

        this.history(_p.level);
      } else {
        this.activeItemsArrry.length = 0;
      }

    }, (err: any) => { });
  }

  // history
  activeItemsArrry: any = [];
  history(_currentLevel) {
    let _wholeName = this.option.cat;

    let _index = _currentLevel - 1;

    // 存在二级叶子
    if (_wholeName.indexOf('--') != -1) {

      this.activeItemsArrry = _wholeName.split('--');

    } else {
      // 只有一级类目
      this.activeItemsArrry.push(_wholeName);

    }

    console.log(this.activeItemsArrry);

    // 查找第一个
    for (let j in this.tree) {

      if (this.tree[j].label == this.activeItemsArrry[_index]) {

        this.treeSelect(this.tree[j], true);

        setTimeout(() => {
          this.setActiveLi(j, _index);
        }, 500);

        break;
      }
    }

    // 一级类目
    this.vm.selectText = this.categoryName.transform(_wholeName);
  }


  // 扩展分支，分支定位
  branch(branch, $event) {

    $event.stopPropagation();

    // 去除
    this.activeItemsArrry = [];
    let aObj;

    // element
    if ($event.target.nodeName == "I") {
      aObj = $($event.target).parent();
    } else {
      aObj = $($event.target);
    }



    let top = aObj.offset().top - aObj.parent().parent().offset().top - aObj.parent().parent().parent().scrollTop() + "px";

    console.log(" top:" + top);


    // 分支定位
    aObj.parent().children('.itemInner').css({ "top": top });


    // 单前元素
    let currentObj = aObj.parent();

    // active
    let activeObj = aObj.parent().siblings('.active');

    if (currentObj.hasClass('active')) {
      console.log('active');

      // 取消之前dactive状态li元素
      console.log(currentObj.find('.itemInner').find('.active').length > 0);

      if (currentObj.find('.itemInner').find('.active').length > 0) {

        currentObj.find('.itemInner').find('.active').removeClass('active');
        // 取消之前全部选择的menu全部显示
        currentObj.find('.itemInner').css({ "display": "none" });
      } else {
        // 设置active菜单
        currentObj.children('.itemInner').css("display", "block");
      }
      // console.log(branch);

      let _cat = branch.data.source;



      // 向Output emit
      this.onChangeCat.emit({ wholeName: _cat.wholeName, categoryId: _cat.id, catName: this.categoryName.transform(_cat.wholeName) });
      return;
    }




    // 设置active状态
    currentObj.addClass('active');
    // 取消之前dactive状态li元素
    activeObj.removeClass('active');
    activeObj.find('.active').removeClass('active');

    // 设置active菜单
    currentObj.children('.itemInner').css("display", "block");

    // 取消之前全部选择的menu全部显示
    activeObj.find('.itemInner').css({ "display": "none" });


    // 请求扩展分支
    this.treeSelect(branch);

  }


  // 请求扩展分支
  treeSelect(branch, initBool: boolean = false) {

    // data
    let item = branch.data.source;

    // param get
    let json = {
      catName: item.wholeName,
      level: item.level + 1
    };

    // 初始化历史(是否有临时)
    if (initBool) {


      this.getHttp(json, branch);

      return;
    }




    // 该分支下是否扩展
    if (branch.noLeaf) {//no

      // console.log(branch.label);

      // text,category
      this.vm.set(branch.label, item.id, item.wholeName);


      // console.log(vm.selectText);
      this.hideElement();


      // 向Output emit
      this.onChangeCat.emit({ wholeName: item.wholeName, categoryId: item.id, catName: item.name });


      return;
    }



    // onlyLeaf 是否有默认值
    if (this.onlyLeaf && this.onlyLeaf === true) {//只有叶子可以点击
      // 不传播数据
    } else {

      // 可以Output emit
      this.vm.set(branch.label, item.id, item.wholeName);


      this.onChangeCat.emit({ wholeName: item.wholeName, categoryId: item.id, catName: item.name });
    }

    this.getHttp(json, branch);

  }

  // 扩展分支ajax
  offEvent: any;
  getHttp(param, branch) {

    this.offEvent = this._service.get(param).subscribe((res: any) => {

      let data = res.data;

      let child = [];

      if (data.length == 0) {
        branch.noLeaf = true;

        this.alertsService.create('info', "暂无数据");
        return;
      }

      for (let j = 0; j < data.length; j++) {

        let menu2 = data[j];

        child.push({
          label: menu2.name,
          noLeaf: (Number(menu2.id) > 0 || (this.option && typeof this.option.onlyLevelOne != 'undefined')) ? true : false,
          children: [],
          data: {
            source: menu2
          }
        });

      }

      branch.children = child;

      // 历史history
      if (this.activeItemsArrry && (this.activeItemsArrry.length > param.level - 1)) {
        for (let k in branch.children) {

          if (branch.children[k].label == this.activeItemsArrry[param.level - 1] && branch.children[k].noLeaf == false) {

            this.treeSelect(branch.children[k], true);

            setTimeout(() => {

              this.setActiveLi(k, param.level);
            }, 500);

            break;
          }
        }
      }

    }, (err) => {


    });

  }

  // 设置active菜单状态li
  setActiveLi(index, level) {
    let liObj = $('.itemInner[level=' + level + ']').children('.itemInnerBox').children('ul').children('li').eq(index);

    let boxObj = $('.itemInner[level=' + level + ']').children('.itemInnerBox');

    console.log(liObj);

    liObj.addClass('active');

    let top = $(liObj).height() * (Number(index));


    // top大于容器的高度
    if (top > 320) {

      $('.itemInner[level=' + (level + 1) + ']').css({ "top": 0 + "px", "display": "block" });
    } else {
      $('.itemInner[level=' + (level + 1) + ']').css({ "top": top + "px", "display": "block" });
    }
  }

  // 隐藏界面
  hideElement() {
    $('.itemInnerAll').css("display", "none");
  }

  // 显示界面
  showElement($event) {
    $event.stopPropagation();

    $event.preventDefault();

    console.log('mo');


    $('.itemInnerAll').css("display", "block");
  }

  // 自动
  autoElement($event) {

    $event.stopPropagation();
    $event.preventDefault();

    console.log($('.itemInnerAll').css('display'));

    // if ($('.itemInnerAll').css('display') == "none") {
    //   $('.itemInnerAll').css("display", "block");
    // } else {
    //   $('.itemInnerAll').css("display", "none");
    // }

  }

}
